<?php

class Controller
{	
	public $SHORT_NAME;
	
	public function __construct()
	{
		logme(get_class($this));
		$this->SHORT_NAME = strtolower(substr(get_class($this), 0, -(strlen("Controller"))));
		logme($this->SHORT_NAME);
	}
	
	private function authenticate()
	{
	    header('WWW-Authenticate: Basic realm="Blog administration"');
	    header('HTTP/1.0 401 Unauthorized');
	    echo "Authentication failed";
	}
	
	function check_authentication($is_admin = false)
	{
		if (!isset($_SERVER['PHP_AUTH_USER'])) 
			$this->authenticate();
		else
		{
		    $name_escaped = sqlite_escape_string($_SERVER['PHP_AUTH_USER']);
			$password_escaped = sqlite_escape_string($_SERVER['PHP_AUTH_PW']);
		
			$sql = "SELECT * FROM Authors WHERE (name = '{$name_escaped}') AND (password = '{$password_escaped}')";
			if ($is_admin)
				$sql .= " AND (is_admin = '1')";
			logme($sql);

			$connection = new PDO(Config::db_connection_string);					
			$result = $connection->query($sql);
			$row = $result->fetch(PDO::FETCH_ASSOC);

			if (!$result || !$row)
			{
				$this->authenticate();
				die("Wrong username or password");
			}
			else
				return true;
		}
	}


	function insert($table, $params, $is_admin_required = false)
	{
		$this->check_authentication($is_admin_required);
		
		$keys = implode(', ', array_keys($params));
		$values_array_escaped = array();
		foreach ($params as $key => $value)
		{
			$values_array_escaped[] = "'" . sqlite_escape_string($value) . "'"; 
		}
		$values_escaped = implode(', ', $values_array_escaped);
		
		$sql = "INSERT INTO {$table} ({$keys}) VALUES ({$values_escaped})";
		$this->db_request($sql);
	}
	
	function update($table, $params, $where_params, $is_admin_required = false)
	{
		$this->check_authentication($is_admin_required);
		
		$assignments = $this->params_to_key_value_string($params);
		$where_assignments = $this->params_to_key_value_string($where_params);

		$sql = "UPDATE {$table} SET {$assignments} WHERE {$where_assignments}";
		$this->db_request($sql);
	}
	
	protected function remove($table, $where_params, $is_admin_required = false)
	{
		$this->check_authentication($is_admin_required);

		$where_assignments = $this->params_to_key_value_string($where_params);

		$sql = "DELETE FROM {$table} WHERE {$where_assignments}";
		$this->db_request($sql);
	}
	
	public function render_view($calling_method)
	{
		//$backtrace = debug_backtrace();
		//echo "<pre>";
		//var_dump($backtrace);
		//$calling_method = $backtrace[1]["function"];
		$view_file = dirname(__FILE__) . "/../views/" . $this->SHORT_NAME . "/" . $calling_method . ".php";
		if (file_exists($view_file))
			include($view_file);
	}
	
}

?>